package com.example.myapplication.ui.movie

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.android_program.data_class.movieImg
import com.example.android_program.data_class.movie_1_1
import com.example.myapplication.MovieDetailsActivity
import com.example.myapplication.R
import com.example.myapplication.ui.home.HomeFragment
import kotlinx.android.synthetic.main.activity_cinema__choose_time_slot.*
import kotlinx.android.synthetic.main.activity_select_cinema.*
import kotlinx.android.synthetic.main.fragment_home.*
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import java.lang.reflect.Field
import java.net.URLEncoder
import kotlin.concurrent.thread

class Cinema_ChooseTimeSlot : AppCompatActivity() {

    val movieImg: ArrayList<movieImg> = ArrayList()
    private var dateList = ArrayList<Date_info>()
    private val timeSlotList = ArrayList<TimeSlot_info>()
    val sever_ip = "192.168.43.8"
    val sever_ip2 = "192.168.31.197"
    val searchMovieDate_jsp = "http://${sever_ip}:8080/JspForAndroid/searchMovieDate.jsp"
    val searchTicketByDate_jsp = "http://${sever_ip}:8080/JspForAndroid/searchTicketByDate.jsp"
    val showAll_Cinema_Movie_jsp = "http://${sever_ip}:8080/JspForAndroid/showAll_cinema_Movie.jsp"
//    val searchMovieDate_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/searchMovieDate.jsp"
//    val searchTicketByDate_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/searchTicketByDate.jsp"
//    val showAll_Cinema_Movie_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/showAll_cinema_Movie.jsp"

    var cinema_name : String? = ""
    var cinema_address : String? = ""
    var movie_Name : String? = ""
    var now_date : String = ""

    private var mRecyclerView: RecyclerView? = null
    private var mAdapter: DateAdapter? = null
    private var mRecyclerView2: RecyclerView? = null
    private var mAdapter2: TimeSlotAdapter? = null
    var cinema_liked = "false"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_cinema__choose_time_slot)

        Recycler_data_cinema()
        Recycler_cinemamovie()

        if (cinema_liked == "false"){
            choise_cinema_collect.setImageResource(R.drawable.choise_movie_sc)
        }
        else if (cinema_liked == "true"){
            choise_cinema_collect.setImageResource(R.drawable.choise_movie_sc_clicked)
        }
        choise_cinema_collect.setOnClickListener {
            if (cinema_liked == "false"){
                cinema_liked = "true"
                choise_cinema_collect.setImageResource(R.drawable.choise_movie_sc_clicked)
            }
            else if (cinema_liked == "true"){
                cinema_liked = "false"
                choise_cinema_collect.setImageResource(R.drawable.choise_movie_sc)
            }
        }

        cinema_name = intent.getStringExtra("cinema_name")
        cinema_address = intent.getStringExtra("cinema_address")
        movie_Name = intent.getStringExtra("movie_name")
        choise_movie_cinema.text = cinema_name
        choise_movie_cinemaname.text = cinema_name
        choise_loaction.text = cinema_address

        //日期，横线RecyView

        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        mRecyclerView = findViewById(R.id.RecyView_ChooseDate)
        mRecyclerView?.layoutManager = layoutManager
        mAdapter = DateAdapter(dateList, applicationContext)
        mRecyclerView?.adapter = mAdapter


//        val layoutManager2 = LinearLayoutManager(this)
//        RecyView_ChooseTime.layoutManager = layoutManager2
//        val adapter2 = TimeSlotAdapter(timeSlotList, applicationContext)
//        RecyView_ChooseTime.adapter = adapter2
        val layoutManager2 = LinearLayoutManager(this)
        mRecyclerView2 = findViewById(R.id.RecyView_ChooseTime)
        mRecyclerView2?.layoutManager = layoutManager2
        mAdapter2 = TimeSlotAdapter(timeSlotList, applicationContext)
        mRecyclerView2?.adapter = mAdapter2


        initDates()//初始化日期
        initTimeSlot()//初始化日期
        
        mAdapter!!.setOnKotlinItemClickListener(object : DateAdapter.IKotlinItemClickListener{
            override fun onItemClickListener(position: Int) {
                //Toast.makeText(applicationContext, "you click ${position}", Toast.LENGTH_LONG).show()
                var i = 0
                while (i < dateList.size){
                    dateList[i].clicked = false
                    i++
                }
                now_date = dateList[position].date
                dateList[position].clicked = true
                mAdapter?.notifyDataSetChanged()

                //更新电影票列表
                getAllTrainInfoJson3(now_date)
               // mAdapter2?.notifyDataSetChanged()
                mRecyclerView2?.setAdapter(mAdapter2)
            }
        })

        choise_movie_back.setOnClickListener {
            val intent = Intent(this, SelectCinemaActivity::class.java)
            setResult(2, intent)
            finish()
        }
    }

    private fun Recycler_cinemamovie() {
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        myrecyclerview_movie.layoutManager = layoutManager
        val adapter = MovieImgAapter(movieImg,myrecyclerview_movie)
        myrecyclerview_movie.adapter = adapter

        val movieSnapHelper = LinearSnapHelper()
        movieSnapHelper.attachToRecyclerView(myrecyclerview_movie)

        myrecyclerview_movie.smoothScrollToPosition(4)
    }

    fun Recycler_data_cinema() {  //前后各两种空白
        /*movieImg.add(movieImg(1,"电影1", R.drawable.block,3))
        movieImg.add(movieImg(2,"电影1", R.drawable.block,3))
        movieImg.add(movieImg(3,"电影1", R.drawable.p1,3))
        movieImg.add(movieImg(4,"电影2", R.drawable.p1,4))
        movieImg.add(movieImg(5,"电影3", R.drawable.p1,5))
        movieImg.add(movieImg(6,"电影4", R.drawable.p1,6))
        movieImg.add(movieImg(7,"电影5", R.drawable.p1,7))
        movieImg.add(movieImg(8,"电影6", R.drawable.p1,8))
        movieImg.add(movieImg(9,"电影7", R.drawable.p1,9))
        movieImg.add(movieImg(10,"电影8", R.drawable.block,9))
        movieImg.add(movieImg(11,"电影9", R.drawable.block,9))*/
        getAllTrainInfoJson4()
    }
    private class cinemamovieViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var cinemamovie_Img: ImageView = view.findViewById(R.id.cinemamovieImg)
    }
    //适配器
    private class MovieImgAapter(val movieImg: List<movieImg>,val myRecyclerView: RecyclerView):
        RecyclerView.Adapter<cinemamovieViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): cinemamovieViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.layout_movieimg, parent, false)
            //点击事件  获取点击的  list 中的数据
            val viewHolder = cinemamovieViewHolder(view)
            viewHolder.cinemamovie_Img.setOnClickListener {
                val position = viewHolder.adapterPosition
                val info = movieImg[position]
                myRecyclerView.smoothScrollToPosition(info.Imgnumber)   //只能往后点？？？

            }
            return viewHolder
        }
        //绑定数据
        override fun onBindViewHolder(holder: cinemamovieViewHolder, position: Int) {
            val info = movieImg[position]
            holder.cinemamovie_Img.setImageResource(info.cinema_movieImg)
        }
        //获取列表行数
        override fun getItemCount(): Int {
            return movieImg.size
        }
    }
    //--------------------------
    private fun initDates(){
        /*dateList.add(Date_info("12月10号", true))
        dateList.add(Date_info("12月10号", false))
        dateList.add(Date_info("12月10号", false))*/
        getAllTrainInfoJson()
    }

    private fun initTimeSlot(){
        /*timeSlotList.add(TimeSlot_info("21:00","23:31散场","国语2D",
            "1号激光厅(广告、冠名招商)", 35.6))
        timeSlotList.add(TimeSlot_info("21:00","23:31散场","国语2D",
            "1号激光厅(广告、冠名招商)", 35.6))*/
        getAllTrainInfoJson2()
    }

    private fun getAllTrainInfoJson(){
        thread {
            try {
                val client = OkHttpClient()

                val requestBody = FormBody.Builder()
                    .add("cinema_name", URLEncoder.encode(cinema_name,"UTF-8"))
                    .add("movie_Name", URLEncoder.encode(movie_Name,"UTF-8"))
                    .build()

                //构建请求
                val request = Request.Builder()
                    .url(searchMovieDate_jsp)
                    .post(requestBody)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
//                txtData.text = responseData
                val result = parseJson(responseData)
                if (responseData != null){
                    runOnUiThread{
                        //修改布局
                        // mAdapter?.notifyDataSetChanged()

                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson(jsonData:String?):String{
        var builder = StringBuilder()
        val tempList = ArrayList<Date_info>()
        try {
            //json数组
            var temp_String = ""
            val jsonArray = JSONArray(jsonData)
            //清空原来的子项
            dateList.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()) {
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                temp_String = jsonObject.getString("dates")
            }
            builder.clear()
            var substring = temp_String.substring(0, temp_String.length)
            val result: List<String> = substring.split(",")
            for (r in result) {
                builder.append("$r--")
                tempList.add(Date_info(r, false))
            }
            //默认选择第一个
            dateList.addAll(tempList)
            dateList[0].clicked = true
            now_date = dateList[0].date
            //initCinemas()
            mAdapter?.notifyDataSetChanged()
            //getAllTrainInfoJson2()

//            Looper.prepare()
//            Toast.makeText(this, builder.toString(), Toast.LENGTH_LONG).show()
//            Looper.loop()
        }catch (e: Exception){
            e.printStackTrace()
        }

        return builder.toString()
    }

    private fun getAllTrainInfoJson2(){
        thread {
            try {
                val client = OkHttpClient()

//                Looper.prepare()
//                Log.d("ttt666：", "cinema_name = ${cinema_name}")
//                Looper.loop()

                val requestBody = FormBody.Builder()
                    .add("ciname_name", URLEncoder.encode(cinema_name,"UTF-8"))
                    .add("movie_Name", URLEncoder.encode(movie_Name,"UTF-8"))
                    .add("date", URLEncoder.encode("12月10号","UTF-8"))
                    .build()

                //构建请求
                val request = Request.Builder()
                    .url(searchTicketByDate_jsp)
                    .post(requestBody)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
//                txtData.text = responseData
                val result = parseJson2(responseData)
                if (responseData != null){
                    runOnUiThread{//????

                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson2(jsonData:String?):String{
        var builder = StringBuilder()
        try {
            //json数组

            val jsonArray = JSONArray(jsonData)
            var tempList = ArrayList<Cinema_info>()

            //清空原来的子项
            timeSlotList.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()) {
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val ciname_name = jsonObject.getString("cinema_name")
                val movie_name = jsonObject.getString("movie_name")
                val date = jsonObject.getString("date")
                val start_time = jsonObject.getString("start_time")
                val end_time = jsonObject.getString("end_time")
                val language = jsonObject.getString("language")
                val hall = jsonObject.getString("hall")
                val price = jsonObject.getDouble("price")

                builder.append("$start_time--$end_time--$language--$hall--$price")

                timeSlotList.add(TimeSlot_info(ciname_name, movie_name, date,
                    start_time, end_time,language,hall,price))

            }
            Looper.prepare()
            Toast.makeText(this, builder.toString(), Toast.LENGTH_LONG).show()
            Looper.loop()
            //cinemalist.addAll(tempList)
            mAdapter2?.notifyDataSetChanged()

            // mAdapter2?.notifyDataSetChanged()
        }catch (e: Exception){
            e.printStackTrace()
        }
        return builder.toString()
    }

    private fun getAllTrainInfoJson3(now_date:String){
        thread {
            try {
                val client = OkHttpClient()

//                Looper.prepare()
//                Log.d("ttt444：", "cinema_name = ${cinema_name}")
//                Looper.loop()
                val requestBody = FormBody.Builder()
                    .add("ciname_name", URLEncoder.encode(cinema_name,"UTF-8"))
                    .add("movie_Name", URLEncoder.encode(movie_Name,"UTF-8"))
                    .add("date", URLEncoder.encode(now_date,"UTF-8"))
                    .build()

                //构建请求
                val request = Request.Builder()
                    .url(searchTicketByDate_jsp)
                    .post(requestBody)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
//                txtData.text = responseData
                val result = parseJson3(responseData)
                if (responseData != null){
                    runOnUiThread{//????

                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson3(jsonData:String?):String {
        var builder = StringBuilder()
        try {
            //json数组

            val jsonArray = JSONArray(jsonData)
            var tempList = ArrayList<Cinema_info>()

            //清空原来的子项
            timeSlotList.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()) {
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val ciname_name = jsonObject.getString("cinema_name")
                val movie_name = jsonObject.getString("movie_name")
                val date = jsonObject.getString("date")
                val start_time = jsonObject.getString("start_time")
                val end_time = jsonObject.getString("end_time")
                val language = jsonObject.getString("language")
                val hall = jsonObject.getString("hall")
                val price = jsonObject.getDouble("price")

                builder.append("$start_time--$end_time--$language--$hall--$price")

                timeSlotList.add(
                    TimeSlot_info(
                        ciname_name, movie_name, date,
                        start_time, end_time, language, hall, price
                    )
                )

            }
            Looper.prepare()
            Toast.makeText(this, builder.toString(), Toast.LENGTH_LONG).show()
            Looper.loop()
            //cinemalist.addAll(tempList)
            mAdapter2?.notifyDataSetChanged()

            // mAdapter2?.notifyDataSetChanged()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return builder.toString()
    }

    private fun getAllTrainInfoJson4(){
        thread {
            try {
                val client = OkHttpClient()


                //构建请求
                val request = Request.Builder()
                    .url(showAll_Cinema_Movie_jsp)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData :String? = response.body?.string()
//                txtData.text = responseData

                val result = parseJson4(responseData)
                if (responseData != null){
                    runOnUiThread{
                        //修改布局
                        // mAdapter?.notifyDataSetChanged()
                        val layoutManager = LinearLayoutManager(this)
                        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
                        myrecyclerview_movie.layoutManager = layoutManager
                        val adapter = MovieImgAapter(movieImg,myrecyclerview_movie)
                        myrecyclerview_movie.adapter = adapter
                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson4(jsonData:String?):String{
        var builder = StringBuilder()
        val tempList = ArrayList<Date_info>()
        try {
            //json数组
            var temp_String = ""
            val jsonArray = JSONArray(jsonData)
            //清空原来的子项
            movieImg.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()) {
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val number = jsonObject.getInt("number")
                val cinema_movie_name = jsonObject.getString("cinema_movie_name")
                val cinema_movie_src = jsonObject.getString("cinema_movie_src")
                val cinema_movie_number = jsonObject.getString("cinema_movie_number")
                builder.append("$number--$cinema_movie_name--${getResourceIdByString(cinema_movie_src)}--$cinema_movie_number")
                movieImg.add(movieImg(number, cinema_movie_name,
                    getResourceIdByString(cinema_movie_src), cinema_movie_number.toInt()))
            }

        }catch (e: Exception){
            e.printStackTrace()
        }

        return builder.toString()
    }

    private fun getResourceIdByString(s: String?): Int {
        try {
            val field: Field = R.drawable::class.java.getField(s)
            return field[null].toString().toInt()
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return 0
    }
}